﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp.DependencyInjection;

namespace Hedou.Abp.Excel.EpPlus
{
    public class EpPlusExcelExporter : EpPlusExcelExporterBase, ITransientDependency
    {

        public EpPlusExcelExporter()
        {

        }

        /// <summary>
        /// 给定一个数据列表 导出到Excel
        /// </summary>
        /// <typeparam name="T">传入的数据类型</typeparam>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName"></param>
        /// <param name="data"></param>
        /// <param name="columnDic">列名 key对应属性名 value对应中文名 key必须包含在类型T中</param>
        /// <returns></returns>
        public FileDto ExportToFile<T>(string fileName, string sheetName, List<T> data, Dictionary<string, string> columnDic) where T : class
        {
            if (data == null || data.Count == 0) return null;
            List<string> columnsDisplay = new List<string>();
            List<string> columns = new List<string>();

            foreach (var pair in columnDic)
            {
                columnsDisplay.Add(pair.Value);
                columns.Add(pair.Key);
            }

            return CreateExcelPackage(fileName, excelPackage =>
            {
                AddSheet(excelPackage, sheetName, data, columnsDisplay, columns);
            });
        }

        protected ExcelWorksheet AddSheet<T>(ExcelPackage excelPackage, string sheetName, List<T> data, List<string> headers, List<string> columns)
            where T : class
        {
            var sheet = excelPackage.Workbook.Worksheets.Add(sheetName);
            sheet.OutLineApplyStyle = true;
            AddHeader(
                sheet,
                headers.ToArray()
            );
            int startRowIndex = 2;
            //日期类型的列
            List<int> dateCols = new List<int>();
            for (int i = 0; i < data.Count; i++)
            {
                var item = data[i];
                //row
                for (int j = 0; j < columns.Count; j++)
                {
                    //col
                    AddObject(sheet, i + startRowIndex, j + 1, item, columns[j].ToLower(), dateCols);
                }
            }

            //格式化日期
            foreach (var colIndex in dateCols)
            {
                var col = sheet.Column(colIndex);
                col.Style.Numberformat.Format = "yyyy-MM-dd HH:mm";
            }

            for (var i = 1; i <= 10; i++)
            {
                sheet.Column(i).AutoFit(sheet.DefaultColWidth, 50);
            }
            return sheet;
        }

        private static void AddObject<T>(ExcelWorksheet sheet, int rowIndex, int colIndex, T item, string colName,
            List<int> dateCols) where T : class
        {
            var type = typeof(T);
            var properties = type.GetProperties();
            foreach (var propertyInfo in properties)
            {
                if (propertyInfo.Name.ToLower() != colName) continue;
                var value = propertyInfo.GetValue(item);
                sheet.Cells[rowIndex, colIndex].Value = value;
                if (propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(Nullable<DateTime>))
                {
                    if (!dateCols.Contains(colIndex))
                        dateCols.Add(colIndex);
                }
                break;
            }
        }
    }
}
